<template>
  <div class="search-suggestion">
    <van-cell icon="search"
    v-for="(text, index) in suggestions"
    :key="index"
    @click="$emit('search',text)"
    >
      <div slot="title" v-html="highlight(text)"></div>
    </van-cell>
  </div>
</template>

<script>
import { getSearchSuggestions } from '@/api/search'
import { debounce } from 'lodash'

export default {
  name: 'SearchSuggestion',
  data () {
    return {
      suggestions: [] // 搜索联想建议数据
    }
  },
  props: {
    searchText: {
      type: String,
      required: true
    }
  },
  watch: {
    searchText: {
      immediate: true, // 该回调将会在侦听开始之后被立即调用
      // 搜索框防抖
      handler: debounce(function (value) {
        this.loadSearchSuggestions(value)
      }, 500)

      // handler(value) {
      //   //watch监听props里面的值变化，value对应的值是searchText
      //   this.loadSearchSuggestions(value);
      // },
    }
  },

  methods: {
    async loadSearchSuggestions (q) {
      try {
        const { data } = await getSearchSuggestions(q)
        this.suggestions = data.data.options
      } catch (error) {
        this.$toast('搜索数据获取失败，稍后重试')
      }
    },
    // 高亮函数
    highlight (text) {
      // 当搜索联想建议词没有时，则结束函数方法
      // replace不能操作为空的数据，会报错
      if (text === null) {
        return
      }
      const highlightStr = `<span class="active">${this.searchText}</span>`
      const reg = new RegExp(this.searchText, 'gi')
      return text.replace(reg, highlightStr)
    }
  }
}
</script>

<style scoped lang="less">
.search-suggestion {
  /deep/ span.active {
    color: #3286fa;
  }
}
</style>
